package com.imax.center.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imax.center.annotation.NoAuth;
import com.imax.center.common.Result;
import com.imax.center.common.ResultCode;
import com.imax.center.config.JwtConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.Map;

@Slf4j
@Component
public class JwtInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtConfig jwtConfig;
    
    @Autowired
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 处理NoAuth注解
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 检查方法上是否有NoAuth注解
            NoAuth methodAnnotation = handlerMethod.getMethodAnnotation(NoAuth.class);
            if (methodAnnotation != null) {
                log.info("方法上有NoAuth注解，跳过token验证");
                return true;
            }
            // 检查类上是否有NoAuth注解
            NoAuth classAnnotation = handlerMethod.getBeanType().getAnnotation(NoAuth.class);
            if (classAnnotation != null) {
                log.info("类上有NoAuth注解，跳过token验证");
                return true;
            }
        }

        // 从Cookie中获取token
        String token = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    token = cookie.getValue();
                    break;
                }
            }
        }

        Map<String, Object> userInfo = token != null ? jwtConfig.parseToken(token) : null;
        if (userInfo != null) {
            request.setAttribute("userInfo", JSONObject.toJSONString(userInfo));
            return true;
        }
        
        response.setContentType("application/json;charset=UTF-8");
        response.setStatus(200);
        PrintWriter writer = response.getWriter();
        writer.write(objectMapper.writeValueAsString(Result.error(ResultCode.UNAUTHORIZED, "未登录或token已过期")));
        writer.flush();
        return false;
    }
} 